#! /bin/bash

# Uncomment below line to enable bash script debugging
# set -x

LOG_FILE='/var/log/remotepc-host/printer.log'
DATA_FILES_PATH='/var/log/remotepc-host/remotePrinter'

# Output "device discovery" information on stdout
if [ "$#" = "0" ]
then
    echo 'direct rpcHostPrinterBackend:/var/log/remotepc-host/remotePrinter "RemotePC_Printer" "Remote Printer by RemotePC"'
    exit 0
fi

# -----------------From here normal backend operation starts-----------------

# check and create directory for storing printer files, installer script also creates it, here it is just for safety
if [ ! -d $DATA_FILES_PATH ]
then
    mkdir -p $DATA_FILES_PATH
    chmod 777 $DATA_FILES_PATH
fi

# close stdout and stderr, redirect stdout to log file, and stderr to where stdout is redirected to (i.e. the log file)
exec 1<&-
exec 2<&-
exec 1>>$LOG_FILE
exec 2<&1

# change file permissions to make it readable by all
chmod 644 $LOG_FILE

echo ''
echo ''
echo '=================================================='
echo "Print job received at time: `date`"
# Input can come from a file or stdin, so mark file as stdin in case input comes from file, and then read from stdin (fd0) in any case
if [ -n "$6" ]
then
    exec <"$6"
fi

PDF_FILE="$DATA_FILES_PATH/rpcHostPrinterFile-$1.pdf"
echo "INFO: writing data to file $PDF_FILE"

if cat - >$PDF_FILE
then
    echo 'INFO: data write successful'
else
    echo "ERROR: data write failed"
    exit 1
fi

# change mode of file so that host process can access it
chmod 644 $PDF_FILE

# Printer data to be sent to RemotePC daemon, #-delimited string
DATA_TO_BE_SENT="PrinterData#$PDF_FILE"

# if this is new backend, then add viewer machine id and printer name also
if [ ! -z "${VIEWER_MACHINE_ID}" ]
then
    DATA_TO_BE_SENT="${DATA_TO_BE_SENT}#${VIEWER_MACHINE_ID}#${PRINTER_NAME}"
fi

# Send the output PDF file name to RemotePC Host daemon via Unix socket
SOCKET_FILE='/var/log/remotepc-host/ho-daemon.sock'
echo "INFO: Checking for socket file: $SOCKET_FILE"
if [ ! -S "$SOCKET_FILE" ]
then
    echo 'ERROR: The socket file for daemon connection is missing.'
    echo "INFO: Contents of /var/log/remotepc-host/: $(ls -la /var/log/remotepc-host/ 2>&1)"
    exit 1
fi

echo "INFO: Socket file found: $(ls -la $SOCKET_FILE 2>&1)"
SOCK_SELINUX_CONTEXT=$(ls -Z "$SOCKET_FILE" 2>/dev/null)
if [ -n "$SOCK_SELINUX_CONTEXT" ]; then
    echo "INFO: SELinux context of socket: $SOCK_SELINUX_CONTEXT"
fi
echo "INFO: Running as user: $(id)"
if [ -r /proc/self/attr/current ]; then
    echo "INFO: Our SELinux context: $(cat /proc/self/attr/current 2>/dev/null)"
fi

echo "INFO: Attempting to send data to daemon via socket"
if command -v python3 >/dev/null 2>&1; then
    echo 'INFO: Using python3 to connect to socket'
    python3 -c "import socket, sys; s=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM); s.connect('/var/log/remotepc-host/ho-daemon.sock'); s.sendall(sys.argv[1].encode('utf-8')); s.close()" "$DATA_TO_BE_SENT"
elif command -v nc >/dev/null 2>&1; then
    echo 'INFO: Using nc to connect to socket'
    echo -n "$DATA_TO_BE_SENT" | nc -UN "$SOCKET_FILE"
else
    echo 'ERROR: python3 or nc is required to connect to unix socket.'
    exit 1
fi

SEND_STATUS=$?
if [ "$SEND_STATUS" != '0' ]
then
    echo "ERROR: Sending filename to daemon failed with exit code: $SEND_STATUS"
    if command -v ausearch >/dev/null 2>&1; then
        echo "INFO: Recent SELinux denials (if any): $(ausearch -m AVC -ts recent 2>/dev/null | tail -5)"
    fi
    exit 1
fi
echo 'INFO: Data sent to daemon successfully'

exit 0
